<html>
<head>
	
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 	
<!--		
<script src="http://code.jquery.com/jquery-latest.js">
</script>
-->
<!--
<script src="http://hdc1112.appspot.com/js/jquery-1.3.2.js" />
-->
<!-- 
<script src="js/jquery-1.3.2.js"/> 
-->
<script>
    var url_server = "http://hdc1112.appspot.com/";
    var url_login = url_server + "login";
    var url_getnote = url_server + "getNotification?sessionID=";
    var url_addchat = url_server + "addChat?sessionID=";
    var url_count = url_server + "count";
	var url_logout=url_server+"logout?sessionID=";
    var sessionID;

    var debug = false;

	var STATUS = { NONE:-1, LOGIN : 0, WAIT : 1, CHAT : 2};
	var status_now;
    //wait mode here!
    var notification_timer;
    function Wait() {
		Set_Status(STATUS.WAIT);

        disable("btn_login");
        enable("btn_logout");
        disable("text_input");
        //disable("area_visual");
		//enable_readonly("text_input");
		enable_readonly("area_visual");
        disable("btn_send");

        Set_Note_Timer();
		Set_Focus("btn_logout");
    }

    function Set_Note_Timer() {
        notification_timer = setInterval("getNotification()", 3000);
    }

	function Chat() {
		Set_Status(STATUS.CHAT);
		disable("btn_login");
		enable("btn_logout");
        enable("text_input");
        //dable("area_visual");
		//disable_readonly("text_input");
		disable_readonly("area_visual");
		enable("btn_send");
		Clear_Area_Content("area_visual");
        Clear_Area_Content("text_input");
		Set_Focus("text_input");
		
		$("#text_input").unbind('keypress').bind('keypress',onkeypress_text_input);
	}
	
    function getNotification() {
		$.ajax({
			url: url_getnote + sessionID,
			timeout: 6000,
			error: function (xmlHttpRequest, error) {
				//d1("no response: " +this.url);
				d1("lost response in this request");
			},
			success:function(responseText) {          
//				d2(responseText);  	
				var json_re = returnJSON(responseText);
				var json_state = json_re.state;
				var chat_array = json_re.chat;
				if (json_state == "wait") {
					Show_Status();
				} else if (json_state == "keep") {
					switch(status_now) {
						case STATUS.WAIT:
							Chat();							
						case STATUS.CHAT:
							//var json_chat=returnJSON(responseText);
							//d2("chat_array.length:"+chat_array.length);
							var chat_arr_len = chat_array.length;
							for(var i=0;i<chat_arr_len;i++) {
								if(i==0) {
									Add_Area_Visual("Stranger:"+decodeURI(chat_array[i]));
								} else {
									Add_Area_Visual("         "+decodeURI(chat_array[i]));
								}
							}
							break;
						default:
							d2("Protocal violated.");
							Logout();
					}
				} else if (json_state == "disconnected") {
					d2("receive disconnect!");
					Logout();
				} else {
					d2("Protocal violated :unknown state!");
					Logout();
				}
			}
		});	
    }
    //wait mode here! //ends

    //count timer! 
    function Refresh_Count() {        
          $.ajax({
          	url: url_count,
            timeout: 4000,
            error: function (xmlHttpRequest, error) {
				dc("Timeout in fetching data.");
            },
            success:function(responseText) {            	
            	var json_re = returnJSON(responseText);
            	var i_all = json_re.all;
            	var i_curr = json_re.current;
            	dc("CHATTING:"+i_curr + " History:" + i_all);
             }
          });        
    }

    var count_timer;
    function Stop_Count_Timer() {
        clearInterval(count_timer);
    }

    function Set_Count_Timer() {
        count_timer = setInterval("Refresh_Count()", 6000);
    }
    //count timer! //ends

    //debug!
    function d0(debug_info) {
        alert(debug_info);
    }

    function d1(debug_info) {
        $("#div_debug").html(debug_info);
    }

    function d2(debug_info) {
        d1(debug_info);
    }

    function dc(debug_info) {
        $("#div_count").html(debug_info);
    }
    //debug! //ends

    //start here!
    $(document).ready(function() {
//    	Resize_Content();
		
		Set_Status(STATUS.NONE);        					

		$("#area_visual").val("Chatting !");
		
		$("#text_input").val("Press Enter to Send !");
        Refresh_Count();
        Set_Count_Timer();
        Login();
    });
    //start here ! //ends

    //Login here!
    function Login() {
		Set_Status(STATUS.LOGIN);
		
        clearInterval(notification_timer);
        enable("btn_login");
        disable("btn_logout");
        disable("text_input");
        //disable("area_visual");
		//enable_readonly("text_input");
		enable_readonly("area_visual");
        disable("btn_send");
		Set_Focus("btn_login");
    }
    //Login here! //ends			

    //utility methods here !
    function disable(id) {
        $("#" + id).attr("disabled", true);
    }

    function enable(id) {
        $("#" + id).removeAttr("disabled");
    }
	
	function enable_readonly(id) {
		$("#"+id).attr("readonly","readonly");
	}
	
	function disable_readonly(id) {
		$("#"+id).removeAttr("readonly");
	}

    function Clear_Area_Content(id) {
        $("#" + id).val(""); //needs improvement?
    }

    function returnJSON(str) {
        return eval('(' + str + ')');
    }
	
	function Set_Status(s) {
		status_now = s;
		Show_Status();

	}
	
	function Set_Focus(id) {
		$("#"+id).focus();
	}
	
	function Show_Status()  {
		switch(status_now) {
			case STATUS.NONE: d2("Initializing ..."); break;
			case STATUS.LOGIN: d2("Login to find a stranger!");break;
			case STATUS.WAIT: d2("Building connection ...");break;
			case STATUS.CHAT: d2("Chatting!");break;						
			default:d2("STATUS.UNKNOWN!");
		}
	}
	
	function Add_Area_Visual(chatstring) {
		$("#area_visual").val($("#area_visual").val()+"\n"+chatstring);
		//$("#area_visual").scrollTop = $("#area_visual").scrollHeight;
		area_visual.scrollTop=area_visual.scrollHeight
	}	
    //utility methods here ! //ends
    //events !
    function onclick_btn_login() {
        disable("btn_login");
        //request login if suc, goto wait,if failed,stop
		  $.ajax({
          	url: url_login,
            timeout: 5000,
            error: function (xmlHttpRequest, error) {
				d2("login timeout");
            	enable("btn_login");
            },
            success:function(responseText) {            	
				var json_re = returnJSON(responseText);
				sessionID = json_re.sessionID;
				d2("login success");
	
				Wait();
             }
          });
		  								
    }

    function Logout() {
		//send logout request!
		  $.ajax({
          	url: url_logout+sessionID
          });	
		
		d2("sent logout");
        Login();
    }
	function onclick_btn_reset() {
		Logout();
	}

	function onclick_btn_send() {
		Add_Area_Visual("You:"+$("#text_input").val());
		var url_addchat_real = url_addchat+sessionID+"&content="+encodeURI($("#text_input").val());
		//d2(url_addchat_real);
		$.ajax({
          	url: url_addchat_real
        });
	}
	
	function onkeypress_text_input(e) {
		if(e.which == 13) {
			onclick_btn_send();
			Clear_Area_Content("text_input");
			$("#text_input").focus();
		}	
	}
    //events ! //ends
    
</script>
<style type="text/css">
#area_visual,	
#btn_login,
#btn_logout,
#text_input,
#btn_send,
table{
	width:100%;
	height:100%;
}

#tr_head,#tr_input{
	height:10%;
}
#tr_main{
	height:75%;
}
#td_input {
	border-color:#0000FF;
}
</style>
</head>
<body>

<table border="0" cellpadding="0" cellspacing="0" >
    <tr id="tr_head">
        <td colspan="3">
        <div id="div_count" align="left"></div></td>
        
    </tr>
    <tr id="tr_main">
      <td colspan="3"><textarea name="textarea" id="area_visual" onpropertychange="this.scrollTop=this.scrollHeight" >
            </textarea></td>
			
    </tr>
    <tr id="tr_input">
        <td width="15%">
            <input type="button" value="Login" id="btn_login" onClick="onclick_btn_login()"
            />
			</td>
			<td width="15%">
            <input type="button" value="Logout" id="btn_logout" onClick="Logout()"
            />        
		</td>
        <td>
            <input type="text" id="text_input">
            </input>        </td>
    </tr>
	<tr>
		<td colspan="3">
			<div id="div_debug" align="right">
		</td>
	</tr>
</table>      

</body>
</html>